package com.config.center.database.event;

import com.alibaba.druid.pool.DruidDataSource;
import com.config.center.database.config.DynamicDataSource;
import com.wpp.constant.Constant;
import com.wpp.register.config.ZkConfigCenter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * @Classname DataSourceEvent
 * @Description TODO
 * @Date 2020/12/12 23:36
 * @Created by wpp25
 */
@Component
public class DataSourceEvent implements ApplicationRunner {

    @Resource
    private ZkConfigCenter zkConfigCenter;

    @Resource
    private DynamicDataSource dynamicDataSource;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        refreshDatSource();
    }

    private void refreshDatSource() {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkConfigCenter.getCuratorFramework(), Constant.ZkConfig.CONFIG_ROOT,Boolean.TRUE);
        // 监听 配置节点下的 数据（数据库连接）的变更
        PathChildrenCacheListener pathChildrenCacheListener = (curatorFramework,event) -> {
            Properties properties = zkConfigCenter.loadConfig();

            DruidDataSource druidDataSource = new DruidDataSource();

            // 设置数据源 连接配置信息
            druidDataSource.setDriverClassName(properties.getProperty(Constant.DataSource.DRIVER_CLASS_NAME));
            druidDataSource.setUrl(properties.getProperty(Constant.DataSource.URL));
            druidDataSource.setUsername(properties.getProperty(Constant.DataSource.USER_NAME));
            druidDataSource.setPassword(properties.getProperty(Constant.DataSource.PASSWORD));

            dynamicDataSource.resetDataSource(druidDataSource);
            System.out.printf("重置数据源信息了 %n");
        };
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        try {
            pathChildrenCache.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
